package com.wcl.demo.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.bumptech.glide.Glide;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.wcl.demo.R;
import com.wcl.demo.model.entity.SearchHimUser;
import com.wcl.demo.network.VolleySingleton;
import com.wcl.demo.utils.DialogUtils;
import com.wcl.demo.utils.ParseManager;
import com.wcl.demo.utils.PreferenceManager;

import java.io.ByteArrayOutputStream;

/**
 * Created by dllo on 15/12/5.
 */
public class PersonInforActivity extends BaseActivity implements View.OnClickListener {
    private ImageView user_head_avatar;//定义显示头像
    private ImageView user_head_headphoto_update;//更新头像按钮
    private ImageView iconRightArrow;//昵称后边的图标
    private ImageView activity_userinfor_bac_Iv;
    private TextView user_nickname;//用户昵称
    private TextView user_username;//用户名
    private ProgressDialog dialog;//定义Dialog
    private RelativeLayout rlNickName;//昵称那一行
    private static final int REQUESTCODE_PICK = 1;//定义常量表示选取图片
    private static final int REQUESTCODE_CUTTING = 2;//定义常量表示剪裁图片
    private SearchHimUser currentUser;//定义当前用户
    private VolleySingleton volleySingleton = VolleySingleton.getInstance();//定义Volley请求

    @Override
    protected int getLayout() {
        return R.layout.activity_user_profile;
    }

    @Override
    protected void initView() {
        user_head_avatar = (ImageView) findViewById(R.id.user_head_avatar);
        user_head_headphoto_update = (ImageView) findViewById(R.id.user_head_headphoto_update);
        user_username = (TextView) findViewById(R.id.user_username);
        user_nickname = (TextView) findViewById(R.id.user_nickname);
        rlNickName = (RelativeLayout) findViewById(R.id.rl_nickname);
        rlNickName.setOnClickListener(this);
        activity_userinfor_bac_Iv = (ImageView) findViewById(R.id.activity_userinfor_bac_Iv);
        activity_userinfor_bac_Iv.setOnClickListener(this);
        user_head_headphoto_update.setOnClickListener(this);
        iconRightArrow = (ImageView) findViewById(R.id.ic_right_arrow);
        initListener();
    }

    /***
     * 获取从设置界面传过来的username
     */
    private void initListener() {
        Intent intent = getIntent();
        String username = intent.getStringExtra("username");
        if (username != null) {
            if (username.equals(EMChatManager.getInstance().getCurrentUser())) {
                user_username.setText(EMChatManager.getInstance().getCurrentUser());
                user_nickname.setText(getCurrentUserNick());
                getBitmap(getCurrentUserAvatar(), user_head_avatar);
            } else {
                user_username.setText(username);
                //asyncFetchUserInfo(username);
            }
        }
    }

    @Override
    protected void initData() {

    }

    /****
     * 修改昵称  成功后设置在TextView上
     *
     * @param nickName
     */
    public void updateRemoteNick(final String nickName) {
        dialog = ProgressDialog.show(this, "正在更新昵称", "请耐心等待");
        boolean updatenick = updateCurrentUserNickName(nickName);
        if (PersonInforActivity.this.isFinishing()) {
            return;
        }
        if (!updatenick) {
            dialog.dismiss();
            Toast.makeText(PersonInforActivity.this, "修改失败", Toast.LENGTH_SHORT)
                    .show();
        } else {
            dialog.dismiss();
            Toast.makeText(PersonInforActivity.this, "修改成功", Toast.LENGTH_SHORT)
                    .show();
            user_nickname.setText(nickName);
        }
    }

    /****
     * 是否修改成功
     *
     * @param nickname
     * @return
     */
    public boolean updateCurrentUserNickName(final String nickname) {
        boolean isSuccess = ParseManager.getInstance().updateParseNickName(nickname);
        if (isSuccess) {
            setCurrentUserNick(nickname);//如果成功获得当前用户信息并将昵称等存到缓存文件中
        }
        return isSuccess;
    }

    /***
     * 获取当前用户昵称
     *
     * @param nickname
     */
    private void setCurrentUserNick(String nickname) {
        getCurrentUserInfo().setNick(nickname);
        PreferenceManager.getInstance().setCurrentUserNick(nickname);
    }

    private void setCurrentUserAvatar(String avatar) {
        getCurrentUserInfo().setAvatar(avatar);
        PreferenceManager.getInstance().setCurrentUserAvatar(avatar);
    }

    private String getCurrentUserNick() {
        return PreferenceManager.getInstance().getCurrentUserNick();
    }

    private String getCurrentUserAvatar() {
        return PreferenceManager.getInstance().getCurrentUserAvatar();
    }

    /***
     * 获取当前用户信息
     *
     * @return
     */
    public synchronized SearchHimUser getCurrentUserInfo() {
        if (currentUser == null) {
            String username = EMChatManager.getInstance().getCurrentUser();
            currentUser = new SearchHimUser(username);
            String nick = currentUser.getNick();
            currentUser.setNick((nick != null) ? nick : username);
            currentUser.setAvatar(currentUser.getAvatar());
        }
        return currentUser;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_nickname:
                final EditText editText = new EditText(PersonInforActivity.this);
                new AlertDialog.Builder(PersonInforActivity.this).setTitle("设置昵称").setIcon(android.R.drawable.ic_dialog_info).setView(editText)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String nickString = editText.getText().toString();
                                if (TextUtils.isEmpty(nickString)) {
                                    Toast.makeText(PersonInforActivity.this, "昵称不能为空", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                updateRemoteNick(nickString);//更新Parse缓存内昵称
                            }
                        }).setNegativeButton("取消", null).create().show();
                break;
            case R.id.user_head_headphoto_update:
                uploadHeadPhoto();//点击个人资料中蓝色相机更换头像
                break;
            case R.id.activity_userinfor_bac_Iv:
                finish();
                break;
        }
    }

    /***
     * 更换头像,选择图片
     */
    private void uploadHeadPhoto() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        builder.setTitle("更换");
        builder.setItems(new String[]{"拍照上传", "本地上传"},
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        switch (which) {
                            case 0:
                                Toast.makeText(PersonInforActivity.this, "暂不支持",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case 1:
                                Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
                                pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                startActivityForResult(pickIntent, REQUESTCODE_PICK);
                                break;
                            default:
                                break;
                        }
                    }
                });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUESTCODE_PICK:
                if (data == null || data.getData() == null) {
                    return;
                }
                startPhotoZoom(data.getData());//剪裁图片
                break;
            case REQUESTCODE_CUTTING:
                if (data != null) {
                    setPicToView(data);
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /***
     * 剪裁图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, REQUESTCODE_CUTTING);
    }

    /**
     * save the picture data
     * 保存图片
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(getResources(), photo);
            user_head_avatar.setImageDrawable(drawable);
            uploadUserAvatar(Bitmap2Bytes(photo));
        }
    }

    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    private void uploadUserAvatar(final byte[] data) {
        dialog = ProgressDialog.show(this, "正在更新头像", "请耐心等待");

        new Thread(new Runnable() {

            @Override
            public void run() {
                final String avatarUrl = ParseManager.getInstance().uploadParseAvatar(data);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        if (avatarUrl != null) {
                            setCurrentUserAvatar(avatarUrl);
                            getBitmap(getCurrentUserAvatar(), user_head_avatar);
                            Toast.makeText(PersonInforActivity.this, "修改头像成功",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(PersonInforActivity.this, "修改头像失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        }).start();
        dialog.show();
    }

    /***
     * 图片请求
     *
     * @param bitmap
     * @param imageView
     */
    private void getBitmap(String bitmap, final ImageView imageView) {
        volleySingleton.getImageResuest(bitmap, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                imageView.setImageBitmap(response);
            }
        });
    }


//    public void asyncFetchUserInfo(String username){
//       ParseManager.getInstance().asyncGetUserInfo(username, new EMValueCallBack<SearchHimUser>() {
//
//           @Override
//           public void onSuccess(SearchHimUser user) {
//               if (user != null) {
//                   if (isFinishing()) {
//                       return;
//                   }
//                   user_nickname.setText(user.getNick());
//                   if (!TextUtils.isEmpty(user.getAvatar())) {
//                       Glide.with(PersonInforActivity.this).load(user.getAvatar()).placeholder(R.mipmap.default_avatar).into(user_head_avatar);
//                   } else {
//                       Glide.with(PersonInforActivity.this).load(R.mipmap.default_avatar).into(user_head_avatar);
//                   }
//               }
//           }
//
//           @Override
//           public void onError(int error, String errorMsg) {
//           }
//       });
//    }


}